package com.example.demo02web.controller;

import cn.hutool.core.io.IoUtil;
import com.example.demo02web.file.core.SysFileService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    private final SysFileService sysFileService;

    @PostMapping(value = "/upload")
    public String upload(@RequestPart("file") MultipartFile file) {
        return sysFileService.uploadFile(file);
    }

    @GetMapping("/{bucket}/{fileName}")
    public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
        sysFileService.getFile(bucket, fileName, response);
    }

    /**
     * 获取resource/file文件下的文件
     */
    @GetMapping("/local/file/{fileName}")
    @SneakyThrows
    public void localFile(@PathVariable String fileName, HttpServletResponse response) {
        ClassPathResource resource = new ClassPathResource("file/" + fileName);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.copy(resource.getInputStream(), response.getOutputStream());
    }

}
